package org.zjvis.datascience.common.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.zjvis.datascience.common.util.db.JDBCUtil;

/**
 * @description 文件写入-数据上传线程
 * @date 2020-06-11
 */
public class WriteThread implements Runnable {
    static Logger logger = LogManager.getLogger(org.zjvis.datascience.common.util.WriteThread.class);

    private int start;
    private int end;
    private CountDownLatch latch;
    private List<List<String>> dataList;
    private String sql;
    private Connection conn;

    public WriteThread(Connection conn, CountDownLatch latch, int start, int end, List<List<String>> dataList, String sql) {
        this.start = start;
        this.end = end;
        this.latch = latch;
        this.dataList = dataList;
        this.sql = sql;
        this.conn = conn;
    }

    @Override
    public void run() {
        System.out.println("线程" + Thread.currentThread().getName() + "正在执行。。线程数据量为:" + (end - start));
        long startTime = System.currentTimeMillis();
        PreparedStatement ps = null;

        try {
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);

            int rows = 0;
            for (int i = start; i < end; i++) {
                int j = 1;
                for (String field : dataList.get(i)) {
                    ps.setString(j, field);
                    j++;
                }
                ps.addBatch();
                //10000次提交一次
                if (++rows % 10000 == 0) {
                    ps.executeBatch();
                    conn.commit();
                    System.out.println("线程" + Thread.currentThread().getName() + "现已完成" + rows + "条记录插入");
                }
            }
            ps.executeBatch();
            // 提交修改
            conn.commit();
            //conn.setAutoCommit(autoCommit);
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
        } finally {
            JDBCUtil.close(conn, ps, null);
            long endTime = System.currentTimeMillis();
            System.out.println("线程" + Thread.currentThread().getName() + "数据写入时间：" + (endTime - startTime) + "ms");
        }

        latch.countDown();
    }

}
